package org.luxor.commons.security.service;

import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.JsonParser;
import org.springframework.security.oauth2.common.util.JsonParserFactory;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.stereotype.Service;

/**
 * Jwt存储功能测试
 *
 * @author Mr.Yan  @date: 2020/8/17
 */
@Service
public class JwtTokenStoreService {
    private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
    private JsonParser objectMapper = JsonParserFactory.create();
    private String verifierKey = new RandomValueStringGenerator().generate();
    private Signer signer = new MacSigner(verifierKey);

    static final JwtTokenStore jwtTokenStore = new JwtTokenStore(new JwtAccessTokenConverter());

    public void readAccessToken(String accessToken) {
        jwtTokenStore.readAccessToken(accessToken);
    }

    public void readAuthentication(OAuth2AccessToken token) {
        jwtTokenStore.readAuthentication(token);
    }

    public void readAuthentication(String token) {
        jwtTokenStore.readAuthentication(token);
    }

    public void readRefreshToken(String refreshToken) {
        jwtTokenStore.readRefreshToken(refreshToken);
    }

    public String createJwtAccessToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        String content;
        try {
            content = objectMapper.formatMap(tokenConverter.convertAccessToken(accessToken, authentication));
        }
        catch (Exception e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
        String token = JwtHelper.encode(content, signer).getEncoded();
        return token;
    }

}
